package com.xteam.xnetworkdisk.utils;

import com.xteam.xnetworkdisk.constant.FIleTypeConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class EmailUtil {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    public static String mailObject = "1706194816@qq.com";

    public static Boolean isQQEmail(String email) {
        final String QQ_EMAIL_REGEX = "[0-9]{5,10}@qq.com";
        Pattern pattern = Pattern.compile(QQ_EMAIL_REGEX);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    public static Boolean isNeteaseEmail(String email) {
        final String NETEASE_EMAIL_REGEX = "[a-zA-Z0-9._%+-]+@(163|126)\\.com";
        Pattern pattern = Pattern.compile(NETEASE_EMAIL_REGEX);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    public void sendEmail(String to, String subject, String text, File attachment) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

        messageHelper.setFrom(mailObject); // 添加发件人邮箱地址
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(text, true); // Set true for HTML content

        // Add attachment if file is not null
        if (attachment != null && attachment.exists()) {
            messageHelper.addAttachment(attachment.getName(), attachment);
        }

        javaMailSender.send(mimeMessage);
    }

    public void sendEmail(String to, String subject, InputStream attachmentStream, Integer type, String filename) throws MessagingException, IOException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

        messageHelper.setFrom(mailObject); // 添加发件人邮箱地址
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);

        // 缓存 InputStream 到字节数组中
        byte[] attachmentBytes;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = attachmentStream.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            attachmentBytes = baos.toByteArray();
        }

        // 使用缓存的字节数组创建 ByteArrayDataSource
        DataSource dataSource = new ByteArrayDataSource(attachmentBytes, "application/octet-stream");

        if (type == FIleTypeConstant.DOCUMENT) {
            // 将流内容转换为文本并设置为 HTML 格式
            String text = new String(attachmentBytes, StandardCharsets.UTF_8);
            text = text.replace("\r\n", "<br>").replace("\n", "<br>");
            messageHelper.setText(text, true);
        } else {
            messageHelper.setText(filename, true);
        }

        messageHelper.addAttachment(filename, dataSource);

        // 发送邮件
        javaMailSender.send(mimeMessage);
    }

    private String readFileContent(File file) throws MessagingException {
        try {
            // 读取文件内容并转为字符串
            return new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new MessagingException("Failed to read file content", e);
        }
    }


    public void sendEmailWithTemplate(String to, String subject, String templateName, Context context) throws MessagingException {
        String body = templateEngine.process(templateName, context);
        sendEmail(to, subject, body, null);
    }

    public String readFileContent(InputStream inputStream) throws IOException {
        // 创建一个 StringBuilder 来存储读取的内容
        StringBuilder content = new StringBuilder();

        // 使用 BufferedReader 读取内容，并指定编码为 UTF-8
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append(System.lineSeparator());
            }
        }

        // 返回读取的内容
        return content.toString();
    }



}
